let textSearch buffer text start =
  let rexp = Str.regexp (String.concat "" [".*\\(";text;".*\\)"]) in
  if (Str.string_match rexp buffer start) then
    print_endline (Str.matched_group 1 buffer)

let textReplace all buffer textsearch textreplace = 
  let strSearch = String.concat "" ["\\(.*\\)";textsearch;"\\(.*\\)"] in
  let strReplace = String.concat "" ["\\1";textreplace;"\\2"] in
  let rexp = Str.regexp strSearch in
  if all then
    print_endline (Str.global_replace rexp strReplace buffer)
  else print_endline (Str.replace_first rexp strReplace buffer)

let buffer = "Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit"

let ask_for_file parent =
  let dialog = GWindow.dialog
      ~parent 
      ~title:"Search & Replace"
      ~height:150
      ~width:400 () in
  let dBoxh = GPack.hbox 
      ~border_width:5
      ~spacing:5
      ~packing:dialog#vbox#pack () in
  let dBoxb = GPack.hbox 
      ~border_width:5
      ~spacing:5
      ~packing:dialog#vbox#pack () in
  let _ = GMisc.label ~text:"Rechercher"
      ~packing:dBoxh#pack () in
  let dTSearch = GEdit.entry
      ~packing:dBoxh#pack () in
  let _ = GMisc.label ~text:"Remplacer"
      ~packing:dBoxb#pack () in
  let dTReplace = GEdit.entry
      ~packing:dBoxb#pack () in
  let dBSearch = GButton.button ~label:"Rechercher" 
      ~packing:dialog#action_area#pack () in
  let dBReplace = GButton.button ~label:"Remplacer 1er" 
      ~packing:dialog#action_area#pack () in
  let dBReplaceAll = GButton.button ~label:"Remplacer tous" 
      ~packing:dialog#action_area#pack () in
  dBSearch#connect#clicked 
      (fun () -> textSearch buffer dTSearch#text 0);
  dBReplace#connect#clicked 
      (fun () -> textReplace false buffer dTSearch#text dTReplace#text);
  dBReplaceAll#connect#clicked 
      (fun () -> textReplace true buffer dTSearch#text dTReplace#text);
  dialog#run ();
  dialog#destroy ()

let main () =
  let _ = GMain.init () in
  let w = GWindow.window 
      ~title:"FileChooser demo"
      ~height:35
      ~width:150 () in
  w#connect#destroy GMain.quit ;

  let b = GButton.button ~label:"S&R Test" ~packing:w#add () in
  b#connect#clicked
    (fun () -> ask_for_file w) ;

  w#show () ;
  GMain.main ()

let _ = main ()

(* compile-command: "ocamlc -I ../src -w s lablgtk.cma gtkInit.cmo filechooser.ml" *)
